<template>
  <div>
    <my-breadcrumb :items="['商品管理', '商品审核']"></my-breadcrumb>
    <Row>
      <i-col span="16">
        <!--spu信息-->
        <div class="spu">
          <!--以表单的方式展现，三行三列，图片在最下方-->
          <h3>商品主信息</h3>
          <Form inline :label-width="80">
            <div>
              <FormItem label="商品标题："><span>{{ spuData.title }}</span></FormItem>
              <FormItem label="商品分类："><span>{{ spuData.goodsClassify }}</span></FormItem>
              <FormItem label="商品单位："><span>{{ spuData.unitId }}</span></FormItem>
              <FormItem label="商品权重："><span>{{ spuData.sortWeight }}</span></FormItem>
            </div>
            <div>
              <FormItem label="商品标签："><span>{{ spuData.goodsLabels }}</span></FormItem>
              <FormItem label="商品备注："><span>{{ spuData.remark }}</span></FormItem>
            </div>
            <div class="goods_images">
              <FormItem label="商品图片：">
                <div style="overflow: hidden;">
                  <!--主图，点击可修改-->
                  <div class="first_img">
                    <Upload
                      :format="['jpg','jpeg','png']"
                      :max-size="2048"
                      :before-upload="handleBeforeUpload"
                      action="#"
                      style="display: inline-block;width:58px;">
                      <div style="width: 58px;height:58px;line-height: 58px;">
                        <img :src="staticUrl + mainImage" alt="主图" width="58">
                      </div>
                    </Upload>
                  </div>
                  <!--其他图片-->
                  <div class="img_i" v-for="(src, index) in goodsImages" :key="index">
                    <img :src="staticUrl + src" alt="图片" width="58">
                    <Icon type="close-circled" color="#ed3f14" size="16" @click="delImage(index)"></Icon>
                  </div>
                  <!--少于五张可上传-->
                  <Upload
                    v-show="goodsImages.length < 4"
                    ref="upload"
                    :show-upload-list="false"
                    :format="['jpg','jpeg','png']"
                    :max-size="2048"
                    :before-upload="handleBeforeUpload"
                    multiple
                    type="drag"
                    action="#"
                    style="display: inline-block;width:58px;margin-left: 8px;">
                    <div style="width: 58px;height:58px;line-height: 58px;">
                      <Icon type="camera" size="20"></Icon>
                    </div>
                  </Upload>
                </div>
                <p><span style="color: #ff9900;">提示：</span>第一张为主图，只能更换不能删除，<span style="color: #ff9900;">点击即可更换</span>；其他为辅图，可删除后重新添加。</p>
              </FormItem>
            </div>
          </Form>
          <div class="btn">
            <Button type="primary" @click="toUpdateSpu">修改商品主信息</Button>
          </div>
        </div>

        <!--sku列表-->
        <div class="sku">
          <!--每个sku一个组件，skuCard，sku数据传递进去，数据分离好操作-->
          <h3>商品sku</h3>
          <div style="margin: 10px 0;">
            <Button type="dashed">+添加sku</Button>
          </div>
          <Row :gutter="16" type="flex" align="middle">
            <i-col span="12" v-for="(sku, index) in skuList" :key="index">
              <sku-card :sku-data="sku" :setups="setups"></sku-card>
            </i-col>
          </Row>
          <div class="btn">
            <Button type="primary">审核通过，商品上架</Button>
            <p><span style="color: #ff9900;">提示：</span>所有价格都不能为0，不能为空，填写完成后务必点击此按钮保存。</p>
          </div>
        </div>
      </i-col>
      <i-col span="8">
        <!--商品详情-->
        <h3>商品详情</h3>
        <div style="margin: 10px 0;text-align: center;">
          <Button type="primary" @click="editRich">编辑商品详情</Button>
        </div>
        <div class="detail">
          <div class="content" v-html="goodsDetail"></div>
        </div>
      </i-col>
    </Row>
    <Modal v-model="showSpuForm" title="修改商品主信息" :styles="{top: '10px'}" width="700">
      <Form :model="spuForm" :label-width="90">
        <FormItem label="商品标题：" prop="title">
          <Input v-model="spuForm.title" placeholder="商品标题，长度最多为30"/>
        </FormItem>
        <FormItem label="商品分类：" prop="goodsCategory">
          <Select v-model="spuForm.goodsCategory" multiple>
            <i-option v-for="item in result.goodsAttr.classify" :value="item.id" :key="item.id">
              <span :class="{childItem: item.parentId}"></span>{{ item.name }}
            </i-option>
          </Select>
        </FormItem>
        <FormItem label="商品单位：" prop="unitId">
          <ul class="list">
            <li v-for="(unit, index) in result.goodsAttr.goodsUnitList" :key="index" @click="selectUnit(unit.id, unit.unit)" :class="{selected: spuForm.unitId === unit.id}">{{ unit.unit }}</li>
          </ul>
          <p><span style="color: #ff9900;">提示：</span>点击选中，但只能选中一个单位（该项为必选项）</p>
        </FormItem>
        <FormItem label="商品标签：">
          <ul class="list">
            <li v-for="(label, index) in result.goodsAttr.goodsLabelList" :key="index" @click="selectLabel(label.id, label.label)" :class="{selected: spuForm.goodsLabels.indexOf(label.id) !== -1}">{{ label.label }}</li>
          </ul>
          <p><span style="color: #ff9900;">提示：</span>点击选中，可多选，但最多只能选两个标签，再次点击取消选中（该项不是必选项）</p>
        </FormItem>
        <FormItem label="商品备注：" prop="remark">
          <Input type="textarea" v-model="spuForm.remark" placeholder="如，本商品进货来源：XX堂，电话：187xxxxxxxx...等信息（可以为空）"/>
        </FormItem>
        <FormItem label="商品权重：" prop="sortWeight">
          <Slider v-model="spuForm.sortWeight" :tip-format="format" @on-change="valueChange" style="width: 540px;"/>
          <span class="sort">({{ sortWeight }})</span>
          <p><span style="color: #ff9900;">提示：</span>权重决定商品在手机主页面的展示排序，权重值为0~100，默认为0，权重越高排序越靠前</p>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center;">
        <Button type="primary" @click="updateBase">修改完成</Button>
      </div>
    </Modal>
    <image-util :fixed-number="[1, 1]" @cropImg="cropImg" ref="crop"></image-util>
    <Modal v-model="showRich" title="编辑商品详情" :styles="{top: '20px'}" width="700">
      <rich-text v-model="goodsDetail" ref="rich"></rich-text>
      <div slot="footer" style="text-align: center;">
        <Button type="primary" @click="submitRich">编辑完成</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import skuCard from './skuCard'
import imageUtil from '../../common/imageUtil'
import richText from '../goods2/richText'
export default {
  name: 'goods-auditing',
  components: {
    skuCard,
    imageUtil,
    richText
  },
  data () {
    return {
      url: {
        page: '/goods/manage/get/goods/info/echo/audit/page',
        setup: '/discount/setup/manage/select/all/branch/customer',
        attr: '/goods/manage/get/category/unit/label/list'
      },

      // spu信息，显示，表单信息
      spuData: {},
      spuForm: {
        goodsLabels: []
      },
      showSpuForm: false,
      sortWeight: 0,
      oldJSON: '',

      // sku列表信息
      skuList: [],

      // 商品详情,主图
      goodsDetail: '',
      showRich: false,
      oldRich: '',
      goodsImages: [], // 路径
      mainImage: '', // 主图，第一张

      // 维护请求计数器
      count: 0,
      result: {
        goodsAttr: {
          goodsLabelList: [],
          goodsUnitList: []
        }
      }, // 请求结果集，三次请求，商品数据，商品属性，价格体系

      setups: [] // 价格体系
    }
  },
  methods: {
    format (val) {
      /*
      * 商品权重格式化提示
      * */
      return val
    },
    valueChange (val) {
      /*
      * 商品权重发生改变提示当前排名百分比
      * */
      this.sortWeight = val
      this.$ajax.get('/goods/manage/real/time/sort/weight', {params: {sortWeight: val}})
        .then(res => {
          if (res.data.success) {
            this.$Message.info('当前权重超过' + res.data.data * 100 + '%的商品')
          }
        })
    },

    getGoodsData () {
      /*
      * 获取商品信息，包括商品spu sku 详情
      * */
      let goodsId = this.$route.params.id
      this.$ajax.get(this.url.page, {params: {goodsId}})
        .then(res => {
          if (res.data.success) {
            this.resHandle(res.data.data, 'goodsData')
          }
        })
    },

    getCustomer () {
      /*
      * 获取价格体系
      * */
      this.$ajax.get(this.url.setup)
        .then(res => {
          if (res.data.success) {
            this.resHandle(res.data.data, 'setups')
          }
        })
    },

    getGoodsAttr () {
      /*
      * 获取商品属性，单位分类标签
      * */
      this.$ajax.get(this.url.attr)
        .then(res => {
          if (res.data.success) {
            this.resHandle(res.data.data, 'goodsAttr')
          }
        })
    },

    resHandle (data, key) {
      /*
      * 异步请求结果处理函数
      * count++
      * */
      this.count++
      this.result[key] = data
      if (this.count === 3) {
        /*
        * 三次请求都已返回
        * key: goodsData, setups, goodsAttr
        * 填充spuData spuForm
        * */
        let goodsData = this.result.goodsData
        this.setups = this.result.setups
        let goodsAttr = this.result.goodsAttr
        goodsAttr.classify = []
        goodsAttr.goodsCategoryTreeList.forEach(item => {
          goodsAttr.classify.push(item)
          goodsAttr.classify.push(...item.childCategoryList)
        })

        for (let i in goodsData.gmInfoEcho) {
          this.spuData[i] = goodsData.gmInfoEcho[i]
          this.spuForm[i] = goodsData.gmInfoEcho[i]
        }
        this.sortWeight = this.spuData.sortWeight
        // 完善spuData
        goodsAttr.goodsUnitList.forEach(item => {
          if (item.id === this.spuData.unitId) {
            this.spuData.unitId = item.unit
          }
        })
        let classify = []
        goodsAttr.classify.forEach(item => {
          if (goodsData.goodsCategory.indexOf(item.id) !== -1) {
            classify.push(item.name)
          }
        })
        this.spuData.goodsClassify = classify.join('，')

        let labels = []
        goodsAttr.goodsLabelList.forEach(item => {
          if (goodsData.goodsLabels.indexOf(item.id) !== -1) {
            labels.push(item.label)
          }
        })
        this.spuData.goodsLabels = labels.join('，')

        // 完善spuForm
        this.spuForm.goodsCategory = goodsData.goodsCategory
        this.spuForm.goodsLabels = goodsData.goodsLabels

        // 商品详情，主图
        this.goodsDetail = goodsData.detailContent
        this.mainImage = goodsData.mainPath
        this.goodsImages = goodsData.goodsMainImagePaths

        // sku列表
        this.skuList = goodsData.gsInfoEcho
      }
    },

    selectUnit (id, unit) {},
    selectLabel (id, label) {},

    toUpdateSpu () {
      /*
      * 点击修改商品主信息触发
      * */
      this.oldJSON = JSON.stringify(this.spuForm)
      this.showSpuForm = true
    },
    updateBase () {
      /*
      * 提交更新spu基本信息
      * 自定义按钮，手动关闭弹窗
      * */
    },

    handleBeforeUpload (e) {
      /*
      * 更换主图，调用切图
      * */
      this.$refs.crop.setImage({e, name: 'spu'})
      return false
    },
    cropImg (data) {
      /*
      * 图片剪切完成回调方法
      * data{imgTime, blob, name}
      * */
      console.log(data)
    },
    delImage (index) {
      /*
      * 删除第一张图片之后的图片
      * */
      this.$Modal.confirm({
        title: '删除图片',
        content: '你确定删除该图片吗？',
        onOk: () => {
          console.log(index)
        }
      })
    },

    editRich () {
      /*
      * 详情图编辑
      * */
      this.oldRich = this.goodsDetail
      this.showRich = true
      this.$nextTick(() => {
        this.$refs.rich.initData(this.goodsDetail)
      })
    },
    submitRich () {
      /*
      * 提交更新详情
      * */
      console.log(this.goodsDetail)
    }
  },
  created () {
    this.getGoodsData()
    this.getCustomer()
    this.getGoodsAttr()
  }
}
</script>

<style scoped>
  .btn{
    padding-top: 20px;
    border-top: 1px solid #dddee1;
    text-align: center;
  }
  .ivu-form-item-content span{
    font-weight: 800;
  }
  .list{
    overflow: hidden;
  }
  .list li{
    float: left;
    height: 28px;
    line-height: 28px;
    margin-right: 20px;
    margin-bottom: 10px;
    border: 1px solid #dddee1;
    padding: 0 10px;
    border-radius: 3px;
    cursor: pointer;
  }
  .list li.selected{
    background-color: #2d8cf0;
    color: #fff;
  }
  .childItem{
    padding-left: 10px;
  }
  .sort{
    position: absolute;
    top: 0;
    right: 0;
    line-height: 0px;
  }
  .sku{
    margin-top: 16px;
    padding-top: 10px;
    border-top: 1px solid #dddee1;
  }
  .detail{
    width: 350px;
    padding: 10px;
    border: 1px solid #000;
    border-radius: 20px;
    height: 660px;
    margin: 0 auto;
  }
  .content{
    overflow-y: auto;
    overflow-x: hidden;
    width: 100%;
    height: 100%;
  }
  .first_img{
    float: left;
    margin-left: 8px;
    cursor: pointer;
  }
  .img_i{
    position: relative;
    float: left;
    margin-left: 8px;
  }
  .img_i i{
    position: absolute;
    top: 2px;
    right: 4px;
  }
</style>
